//
//  DownLoadOffLineViewController.m
//  NSURLSessionStudyDemo
//
//  Created by 赵忠鹏 on 2018/5/7.
//  Copyright © 2018年 内蒙小猿. All rights reserved.
//

#import "DownLoadOffLineViewController.h"

@interface DownLoadOffLineViewController ()<NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *OffLineProgress;
@property (nonatomic, strong) NSOutputStream *stream;
@property (nonatomic, assign) NSInteger totalLength;
@property (nonatomic, assign) NSInteger currentLength;
@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
@property (nonatomic, strong) NSURLSession *session;

@end

#define FileName @"minion_03.mp4"
#define FileLength @"minion"

@implementation DownLoadOffLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //计算当前的进度
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *fullPath = [caches stringByAppendingPathComponent:FileLength];
    NSLog(@"%@", fullPath);
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:fullPath];
    
    if (dict) {
        NSInteger total = [[dict objectForKey:FileLength] integerValue];
        NSLog(@"%zd---------",total);
        self.totalLength = total;
    }
    if (self.totalLength !=0) {
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *cachesFullPath = [cachesPath stringByAppendingPathComponent:FileName];
        
        self.OffLineProgress.progress = 1.0 * [self getCurrentFileSize:cachesFullPath] /self.totalLength;
    }
    
    
}

- (NSURLSessionDataTask *)dataTask{
    if (_dataTask == nil) {
        
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *cachesFullPath = [cachesPath stringByAppendingPathComponent:FileName];
        
        self.currentLength = [self getCurrentFileSize:cachesFullPath];
        
        //1.创建session,并设置代理
        
        //2.创建task
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"]];
        
        //设置请求头
        NSString *header = [NSString stringWithFormat:@"bytes=%zd-",self.currentLength];
        [request setValue:header forHTTPHeaderField:@"Range"];
        NSLog(@"%@", request);
        
        NSLog(@"+++++++++++++++++++=%@",header);
        
        _dataTask = [self.session dataTaskWithRequest:request];
    }
    return _dataTask;
}


- (NSURLSession *)session{
    if (_session == nil) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

// 开始
- (IBAction)beginButtonClick:(id)sender {
    [self.dataTask resume];
}

// 暂停
- (IBAction)stopButtonClick:(id)sender {
    [self.dataTask suspend];
}

// 继续下载
- (IBAction)continueButtonClick:(id)sender {
    [self.dataTask resume];
}

#pragma mark Method
/**
 获取指定路径下文件的大小
 @param filePath 文件路径
 @return 文件大小
 */
-(NSInteger)getCurrentFileSize:(NSString *)filePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSDictionary *dic = [fileManager attributesOfItemAtPath:filePath error:nil];
    
    return [dic[@"NSFileSize"] integerValue];
}



/**
 存储最大长度

 @param lengthName 存的是那个 name 的长度
 @param length 数据长度
 */
- (void)savaTotalLength:(NSString *)lengthName realLength:(NSInteger)length{
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *cachesFullPath = [cachesPath stringByAppendingPathComponent:lengthName];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    [dic setValue:@(length) forKey:lengthName];
    [dic writeToFile:cachesFullPath atomically:YES];
    
}


#pragma mark NSURLSessionDataDelegate
#pragma mark ----------------------
/*
 1.接收到服务器响应的时候调用
 */
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    
    //拿到文件的大小
    self.totalLength = response.expectedContentLength + self.currentLength;
    NSLog(@"expectedContentLength:%lld",response.expectedContentLength);
    NSLog(@"文件大小%zd",self.totalLength);
    
    [self savaTotalLength:FileLength realLength:self.totalLength];
    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *fullPath = [caches stringByAppendingPathComponent:FileName];
    
    NSLog(@"%@",fullPath);
    //1.创建输出流,如果没有文件那么会创建
    NSOutputStream *stream = [[NSOutputStream alloc]initToFileAtPath:fullPath append:YES];
    
    [stream open];
    self.stream = stream;
    
    NSLog(@"didReceiveResponse");
    
    completionHandler(NSURLSessionResponseAllow);
}

/*
 2.接收到服务器返回数据的时候调用,该方法可能会被调用多次
 */
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    //    NSLog(@"didReceiveData");
    [self.stream write:data.bytes maxLength:data.length];
    
    self.currentLength += data.length;
    NSLog(@"%f",1.0 * self.currentLength/ self.totalLength);
    self.OffLineProgress.progress = 1.0 * self.currentLength/ self.totalLength;
}

/*
 3.当请求完成之后调用,如果错误,那么error有值
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    [self.stream close];
    NSLog(@"didCompleteWithError");
}

- (void)dealloc
{
    if (self.session) {
        [self.session invalidateAndCancel];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
